from sklearn import svm
import numpy as np
import pandas as pd
import datetime
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import MinMaxScaler


imp_median = SimpleImputer(strategy="median")
# 实现归一化
scaler = MinMaxScaler()

file_list = [
    "ETHUSDT",
    'DJI',
    'SHA',
    'BNBUSDT',
    'LEOUSDT',
    'HTUSDT',
]


def cacular_date(date_, day_):
    if isinstance(date_, datetime.date):
        date_ = date_.strftime("%Y-%m-%d")
    date_list = list()
    if day_ > 0:
        for d_ in range(day_):
            date_t = (datetime.datetime.strptime(date_, "%Y-%m-%d")
                     + datetime.timedelta(days=d_)).strftime("%Y-%m-%d")
            date_list.append(date_t)
        return date_list, date_list[-1]
    else:
        return (datetime.datetime.strptime(date_, "%Y-%m-%d")
                + datetime.timedelta(days=day_)).strftime("%Y-%m-%d")


def get_df(filename, date_list):
    file = "data/%s/data.csv" % filename
    df = pd.read_csv(file)
    df = df.set_index('open_time')
    if filename == "DJI" or filename == "SHA":
        for date_ in date_list:
            if date_ not in df.index:
                tmp = df.loc[cacular_date(date_, -1)]
                tmp['open_time'] = date_
                tmp = pd.DataFrame(tmp.to_dict(), index=[0]).set_index('open_time')
                df = pd.concat([df, tmp])
                df.sort_values("open_time", inplace=True)
    return df


def get_12_data(tmp_date, full_date_list):
    start_date = tmp_date
    date_list, end_date = cacular_date(start_date, 12)
    print(start_date, end_date)
    index_file_list = list()
    for filename in file_list:
        df = get_df(filename, full_date_list)
        dfs_ = df[start_date: end_date]

        for date_ in date_list:
            if date_ not in dfs_.index:
                tmp = dfs_.loc[cacular_date(date_, -1)]
                tmp['open_time'] = date_
                tmp = pd.DataFrame(tmp.to_dict(), index=[0]).set_index('open_time')
                dfs_ = pd.concat([dfs_, tmp])
                dfs_.sort_values("open_time", inplace=True)
        # 把dfs_转换成List
        tmp_list = dfs_.values.tolist()
        result_ = scaler.fit_transform(tmp_list) * 100
        # 这里的result_是单个文件的12天的特征信息，需要把几个指标文件组合到一起。
        index_file_list.extend(result_.tolist())

    return index_file_list


def get_18_price(date_, df):
    date_12 = cacular_date(date_, 12)[1]
    date_18 = cacular_date(date_, 18)[1]
    high_price_12 = df.loc[date_12]['high']
    low_price_18 = df.loc[date_18]['low']
    profit = low_price_18 - high_price_12
    profit_margin = profit/high_price_12
    if profit_margin > 0.03:
        return 1
    else:
        return 0


def getXy():
    # date_list是begin_date 一直到昨天的日期的list
    index_list = list()
    target_list = list()
    for date_ in date_list:
        if cacular_date(date_, 18)[1] <= date_yesteday:
            # 这里的index_data是12天的指标数据的特征 [[1,2,3,4,5], [2,2,3,4,5], ... , [12,2,3,4,5]]
            index_data = get_12_data(date_, date_list)
            index_list.append(index_data)
            target = get_18_price(date_, currency_df)
            target_list.append(target)
        else:
            break
    index_array = np.array(index_list)
    nsamples, nx, ny = index_array.shape
    X_array = index_array.reshape((nsamples, nx * ny))
    target_array = np.array(target_list)
    return X_array, target_array


if __name__ == '__main__':

    # date_today = datetime.date.today()
    # toDo
    date_today = cacular_date(datetime.date.today(), -1)
    date_yesteday = cacular_date(date_today, -1)

    beigin_date = cacular_date(date_today, -365)

    date_list = cacular_date(beigin_date, 365)[0]

    currency_df = get_df("ETHUSDT", date_list)

    X_set, target_array = getXy()

    np.savetxt("X.csv", X_set, delimiter=",")
    np.savetxt("y.csv", target_array, delimiter=",")
